<?php
namespace app\web\home;


use app\web\model\Order as myModel;
use app\web\model\OrderLogs;
use app\web\model\Shop;
use app\web\model\Project;
use app\web\model\User;
use app\web\model\Technician;
use app\web\model\Config;
use app\web\model\Traffic;
use app\lib\model\Price;
use app\lib\model\Tool;
use app\web\model\Coupon;
use app\web\model\Scheduling;
use app\web\model\UserBalance;
use app\web\model\ShopBalance;
use app\web\model\TechnicianBalance;
use app\web\model\UserAddress;
use app\web\model\UserIntegral;
use app\web\model\Comment;
use app\web\model\Blacklist;
use think\Db;
use Yansongda\Pay\Pay;

/**
 * 订单
 */
class Order extends Base 
{
	
	/**
	 * 用户端订单列表
	 * [list description]
	 * @param  integer $status [description]
	 * @return [type]          [description]
	 */
	public function list($status = 0)
	{
		$where['a.user_id'] = $this->uid;
		if($status > 0) $where['a.status'] = $status-1;
		$field = 'a.id,a.order_no,a.money,b.nickName,a.image,a.project_name,a.number,a.status,a.travel_price,a.coupon_money,a.rate,a.integral_money,a.pay_money+a.balance_money+a.plus_money as pay_money';
		return show(200,'用户端订单列表',$this->getOrderList($where,$field));
	}
	/**
	 * 技师端订单列表
	 * [getList description]
	 * @param  integer $status [description]
	 * @return [type]          [description]
	 */
	public function getList($status = 0){
		$t_id = $this->getCurrentId();
		$where['a.technician_id'] = $t_id;
		$where['a.pay_status'] = 1;
		if($status > 0) $where['a.technician_status'] = $status-1;

		$field = 'a.id,a.order_no,a.money,b.nickName,a.image,a.project_name,a.number,a.travel_price,a.coupon_money,a.rate,a.integral_money,a.pay_money+a.balance_money+a.plus_money as pay_money,a.technician_status';
		return show(200,'技师端订单列表',$this->getOrderList($where,$field));
	}
	/**
	 * 商家端订单列表
	 * [shopOrderList description]
	 * @param  integer $status [description]
	 * @return [type]          [description]
	 */
	public function shopOrderList($status = 0)
	{
		$shop_id = $this->getCurrentId();
		$where['a.shop_id'] = $shop_id;
		$where['pay_status'] = 1;
		if($status > 0) $where['a.shop_status'] = $status-1;
		$field = 'a.id,a.order_no,a.money,b.nickName,a.image,a.project_name,a.number,a.travel_price,a.coupon_money,a.rate,a.integral_money,a.pay_money+a.balance_money+a.plus_money as pay_money,a.shop_status';
		return show(200,'技师端订单列表',$this->getOrderList($where,$field));
	}
	/**
	 * 用户订单详情
	 * [info description]
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function info($id)
	{
		$field = 'a.id,a.order_no,a.consignee,a.order_time,a.order_distance,a.mobile,concat(a.province,a.city,a.area) as user_area,a.address,a.order_notes,a.image,a.project_name,a.number,a.money,a.service_time,a.plus_money,a.travel_price,a.coupon_money,a.rate,a.integral_money,a.pay_money+a.balance_money+a.plus_money as pay_money,a.create_time,b.nickName,b.shop_mobile as technician_mobile,ifnull(c.shop_name,"无") as shop_name,ifnull(c.shop_mobile,"") as shop_mobile,concat(b.province,b.city,b.area) as technician_area,b.address as technician_addr,a.pay_time,a.refund_time,a.technician_complete_time as complete_time';
		if($this->appkey == 0){
			$field .= ',a.status,a.platform_service_money,a.refund_travel_price,a.delay_work_money,a.tot_money-a.tot_platform as refunded_amount';
		}elseif($this->appkey == 1){
			$field .= ',a.technician_status,a.technician_service,a.delay_work_money,a.platform_service_money,a.refund_travel_price,a.tot_money-a.tot_platform as refunded_amount,d.is_face,b.avatarUrl';
		}else{
			$field .= ',a.status,a.platform_service_money,a.refund_travel_price,a.delay_work_money,a.tot_money-a.tot_platform as refunded_amount';
		}
		$list = myModel::alias('a')
						->leftjoin('technician b','b.id=a.technician_id')
						->leftjoin('project e','e.id=a.project_id')
						->leftjoin('category d','d.id=e.category_id')
						->leftjoin('shop c','c.id=b.shop_id')
						->where('a.id',$id)
						->field($field)
						->order('id desc')
						->find()->toArray();
		$list['service_time'] /= 60;
		if($this->appkey == 0 && $list['status'] > 2){
			$list['technician_mobile'] = '****';
			$list['shop_mobile'] = '';
		} 
		if($this->appkey == 1 && $list['technician_status'] > 1){
			$list['mobile'] = '****';
		} 
		if($this->appkey == 2 && $list['shop_status'] > 1){
			$list['mobile'] = '****';
		} 
		$list['pay_time'] = $list['pay_time'] ? date('Y-m-d H:i',$list['pay_time']) : '';
		$list['refund_time'] = $list['refund_time'] ? date('Y-m-d H:i',$list['refund_time']) : '';
		$list['complete_time'] = $list['complete_time'] ? date('Y-m-d H:i',$list['complete_time']) : '';
		$logs_field = 'id,contents'.$this->appkey.' as content,mobile,create_time,ifnull(longitude,"") as longitude,ifnull(latitude,"") as latitude';
		$list['logs'] = OrderLogs::where(['order_id'=>$id])->field($logs_field)->order('id')->all();
		return show(200,'订单详情',$list);
	}
	/**
	 * 已到账 待到帐订单详情
	 * [find description]
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function find($id)
	{
		if($this->appkey == 1){   //技师端
			
			$data = TechnicianBalance::get($id);
			// $s_change_balance = ShopBalance::where([['order_id','=',$data['order_id']],['balance_type','in','1,2']])->sum('change_balance');
		}else{   //商家端
			$data = ShopBalance::get($id);
			// $t_change_balance = TechnicianBalance::where([['order_id','=',$data['order_id']],['balance_type','in','1,2']])->sum('change_balance');
		}
		
		$field = 'a.id,a.shop_id,a.technician_id,a.order_no,a.consignee,a.order_time,a.order_distance,a.mobile,concat(a.province,a.city,a.area) as user_area,a.address,a.order_notes,a.image,a.project_name,a.number,a.money,a.service_time,a.plus_money,a.travel_price,a.coupon_money,a.rate,a.integral_money,a.pay_money+a.balance_money+a.plus_money as pay_money,a.create_time,a.pay_time,a.refund_time,a.technician_complete_time as complete_time,a.status,a.delay_work_money,a.refund_travel_price,a.platform_service_money,a.tot_platform,a.shop_plus_commission+a.shop_commission as s_change_balance,a.technician_plus_commission+a.technician_commission as t_change_balance,a.order_money-a.tot_platform as refunded_amount';
		$list = myModel::alias('a')
						->leftjoin('technician b','b.id=a.technician_id')
						->leftjoin('project e','e.id=a.project_id')
						->leftjoin('category d','d.id=e.category_id')
						->leftjoin('shop c','c.id=b.shop_id')
						->where('a.id',$data['order_id'])
						->field($field)
						->order('id desc')
						->find()->toArray();
		$list['pay_time'] = $list['pay_time'] ? date('Y-m-d H:i') : '';
		$list['refund_time'] = $list['refund_time'] ? date('Y-m-d H:i') : '';
		$list['complete_time'] = $list['complete_time'] ? date('Y-m-d H:i') : '';

		$list['service_time'] /= 60;
		if($list['status']!=5){
			$list['refunded_amount'] = 0;
		}
		$technician = Technician::get($list['technician_id']);

		if($this->appkey == 1){   //技师端
			$list['order_rate'] = Price::pricecalc(Price::pricecalc(Price::pricecalc(1,'-',$technician['order_rate']),'-',$technician['shop_order_rate']),'*',100);
			$list['plus_rate'] = Price::pricecalc(Price::pricecalc(Price::pricecalc(1,'-',$technician['plus_rate']),'-',$technician['shop_plus_rate']),'*',100);
		}else{   //商家端
			$list['order_rate'] = $technician['shop_order_rate'];
			$list['plus_rate'] = $technician['shop_plus_rate'];
		}
		$list['order_rate'] = (float)$list['order_rate'];
		$list['plus_rate'] = (float)$list['plus_rate'];
		return show(200,'订单详情',$list);
	}
	private function getOrderList($where,$field){
		$list = myModel::alias('a')->where($where)
						->field($field)
						->leftjoin('technician b','b.id=a.technician_id')
						->order('a.id desc')
						->paginate();

		return $list;
	}
	/**
	 * 用户下单
	 * [create description]
	 * @return [type] [description]
	 */
	public function create()
	{
		$post = input('post.');
		$scheduling = Scheduling::get($post['scheduling_id']);
		if(!$scheduling) return show(400,'请选择服务时间');
		if($scheduling['status'] != 0) return show(400,'该时间不可预约');
		
		$technician = Technician::get($post['t_id']);

		$project = Project::get($post['project_id']);
	
		$user = User::get($this->uid);
		
		//接单形式0商家接单就默认技师接单成功1技师接单就默认接单成功了2商家和技师都必须同意接单
		$receiving_order_type = 1;
		if($technician['shop_id'] > 0){
			$receiving_order_type = Shop::where('id',$technician['shop_id'])->value('receiving_order_type');
		}
		$addr = UserAddress::get($post['addr_id']);
		$order_data = [
			'consignee' => $addr['consignee'],
			'mobile' => $addr['mobile'],
			'province' => $addr['province'],
			'city' => $addr['city'],
			'area' => $addr['area'],
			'address' => $addr['address'],
			'longitude' => $addr['longitude'],
			'latitude' => $addr['latitude'],
			'order_type' => $technician['shop_id'] == 0 ? 0 : 1,
			'order_no' => $this->getOrderNo(),
			'user_id' => $this->uid,
			'shop_id' => $technician['shop_id'],
			'technician_id' => $technician['id'],
			'project_id' => $project['id'],
			'order_distance' => $post['order_distance'],
			'project_name' => $project['project_name'],
			'service_time' => ((int)$project['service_time'])*60,    //服务时长
			'money' => $project['money'],
			'image' => explode(',', $project['image'])[0],
			'number' => (int)$post['number'],
			'service_money' => Price::pricecalc($post['number'],'*',$project['money']),   //服务总金额
			'order_time' => (int)$scheduling['start_time'],    //预约开始时间
			'travel_price' => $post['travel_price'],    //路费
			'coupon_id' => $post['coupon_id'] ?? 0,
			'plus_money' => 0,
			'coupon_money' => 0,
			'integral' => (isset($post['integral']) && $post['integral'] == 1) ? $user->integral : 0,
			'integral_money' => 0,
			'rate' => 1,
			'pay_type' => $post['pay_type'] ?? 0,
			'order_notes' => $post['order_notes'] ?? '',
			'pay_status' => 0,
			'receiving_order_type' => $receiving_order_type,
			'status' => 0
		];
		
		Blacklist::checkOrder($order_data);
		$order_data['tot_money'] = Price::pricecalc($order_data['service_money'],'+',$order_data['travel_price']);   //订单总金额
		$end_time = $order_data['number']*$order_data['service_time']+$order_data['order_time'];
		$res = Scheduling::where([['technician_id','=',$order_data['technician_id']],['start_time','>=',$order_data['order_time']],['start_time','<',$end_time],['status','=',0]])->field('FROM_UNIXTIME(start_time) as start_time')->select();
		if($order_data['order_time'] < time()){
			return show(400,'不能预约过去的时间');
		}
		//不验证排班信息
		// if(count($res) < ceil(($order_data['number']*$order_data['service_time'])/1800)){
		// 	return show(400,'排班不够,不可预约');
		// }
		if($order_data['coupon_id'] > 0){   //优惠券支付金额
			$coupon = Coupon::get($order_data['coupon_id']);
			if($coupon->status == 1) return show(400,'该优惠券不可使用');
			if(bccomp($order_data['service_money'], $coupon['full_money'],2) == -1){
				return show(400,'该优惠券满'.$coupon['full_money'].'元可用');
			}
			if($order_data['order_type'] == 0 && $coupon['shop_id'] > 0) return show(400,'该优惠券不可使用');
			if($order_data['order_type'] == 1 && $coupon['technician_id'] > 0) return show(400,'该优惠券不可使用');
			$order_data['coupon_money'] = $coupon['money'];  //优惠券支付金额
		}
		if($order_data['integral'] > 0){  //积分抵扣
			if(bccomp($order_data['integral'], $user->integral) == 1) return show(400,'积分不足');
			$integral_rate = Config::getConfig('integral_rate');
			if(!$integral_rate) return show(400,'未设置积分抵扣比');
			$order_data['integral_money'] = Price::pricecalc($order_data['integral'],'*',$integral_rate); 
		}
		$order_data['order_money'] = Price::pricecalc(Price::pricecalc($order_data['tot_money'],'-',$order_data['integral_money']),'-',$order_data['coupon_money']);

		if($order_data['pay_type'] == 0){
			if(bccomp($order_data['order_money'],$user->balance,2) == 1) return show(400,'余额不足');
			$order_data['balance_money'] = $order_data['order_money'];
			$order_data['pay_status'] = 1;
			$order_data['pay_time'] = $this->request->time();
			$order_data['status'] = 1;
		}
		//店铺应得金额
		$order_data['shop_commission'] = myModel::shopCommission($order_data);
		//平台应得金额
		$order_data['platform_commission'] = myModel::platformCommission($order_data);
		//计算技师应得金额
		$order_data['technician_commission'] = Price::pricecalc(Price::pricecalc($order_data['tot_money'],'-',$order_data['shop_commission']),'-',$order_data['platform_commission']);
		Db::startTrans();
		$order = myModel::create($order_data);
		if($order->isEmpty()) return show(400,'预约失败');
		$order_logs = OrderLogs::create([
			'logs_type' => 0,
			'order_id' => $order->id,
			'contents0' => '您于'.date('Y-m-d H:i').' 创建订单',
			'contents1' => date('Y-m-d H:i').' 创建订单',
			'contents2' => date('Y-m-d H:i').' 创建订单',
			'mobile' => $order_data['mobile']
		]);
		if($order_data['shop_commission'] > 0){  //店铺应得佣金
			$res = ShopBalance::change($order_data['shop_id'],$order_data['shop_commission'],1,'订单待结算',$order->id,0);
			if(!$res){
				Db::rollback();
				return show(400,'预约失败');
			}
		}
		if($order_data['technician_commission'] > 0){  //技师应得佣金
			$res = TechnicianBalance::change($order_data['technician_id'],$order_data['technician_commission'],1,'订单待结算',$order->id,0);
			if(!$res){
				Db::rollback();
				return show(400,'预约失败');
			}
		}
		if($order_logs->isEmpty()){
			Db::rollback();
			return show(400,'预约失败');
		}
		if($order_data['coupon_id'] > 0){  //修改优惠券状态为已使用
			$coupon->status = 1;
			$coupon->use_time = $this->request->time();
			if(!$coupon->save()){
				Db::rollback();
				return show(400,'预约失败');
			}
		}
		if($order_data['integral'] > 0){
			$res = UserIntegral::change($this->uid,-$order_data['integral'],1,$order->id);
			if(!$res){
				Db::rollback();
				return show(400,'预约失败');
			}
		}
		if($order_data['pay_status'] == 1){   //扣减余额
			$res = UserBalance::change($this->uid,-$order_data['balance_money'],1,'成功预约技师',$order->id);
			if(!$res){
				Db::rollback();
				return show(400,'预约失败');
			}
			$technician->order_number = $technician->order_number + (int)$order_data['number'];
			if(!$technician->save()){
				Db::rollback();
				return show(400,'预约失败');
			}
			$project->order_number = $project->order_number + (int)$order_data['number'];
			if(!$project->save()){
				Db::rollback();
				return show(400,'预约失败');
			}
			
			$order_logs = OrderLogs::create([
				'logs_type' => 1,
				'order_id' => $order->id,
				'contents0' => '通过余额支付完成付款',
				'contents1' => '通过余额支付完成付款',
				'contents2' => '通过余额支付完成付款',
				'mobile' => $order_data['mobile']
			]);
			if($order_logs->isEmpty()){
				Db::rollback();
				return show(400,'预约失败');
			}
		}
		$res = Scheduling::where([['technician_id','=',$order_data['technician_id']],['start_time','>=',$order_data['order_time']],['start_time','<',$end_time],])->update(['order_id'=>$order->id,'update_time'=>time()]);
		if(!$res){
			Db::rollback();
			return show(400,'预约失败');
		}
		Db::commit();
		if($order_data['pay_status'] == 1){
			$send_mobile = Technician::where('id',$order_data['technician_id'])->value('shop_mobile');
			if($order_data['shop_id'] > 0){
				$send_mobile .= ','.Shop::where('id',$order_data['shop_id'])->value('shop_mobile');
			}
			//支付成功发送短信通知给技师和商户
			$model = new \app\lib\model\Ylysms();
			$rest = $model->sendTemplateSMS($send_mobile,[],config('api.ylysms_new_order_id'));

		}
		return show(200,'预约成功',['order_id'=>$order->id,'order_no'=>$order_data['order_no'],'pay_status'=>$order_data['pay_status']]);
	}
	/**
	 * 下单页面选择了地址技师计算 订单距离 路费
	 * [addressResolution description]
	 * @param  [type] $address [description]
	 * @param  [type] $t_id    [description]
	 * @return [type]          [description]
	 */
	public function addressResolution($addr_id, $t_id,$scheduling_id)
	{
		// $data = Tool::addressResolution($address);
		$addr = UserAddress::get($addr_id);
		$technician = Technician::get($t_id);
		$data['distance'] = Tool::getDistance($addr['longitude'],$addr['latitude'],$technician['longitude'],$technician['latitude']);
		if(bccomp($data['distance'], $technician['service_area'],2) == 1){
			return show(400,'距离太远不可预约');
		}
		$is_day = $this->isDay($scheduling_id);
		$traffic_id = $technician->traffic_id;

		$traffic = Traffic::get($traffic_id);
		if(!$traffic){
			$traffic = Traffic::order('traffic_number')->limit(1)->find();
		}
		$data['travel_price'] = 0;
		if(!$traffic || bccomp($traffic->traffic_number, $data['distance'],2) == -1 || $is_day == 0){
			$url = 'https://apis.map.qq.com/ws/direction/v1/driving/?from='.$technician['latitude'].','.$technician['longitude'].'&to='.$addr['latitude'].','.$addr['longitude'].'&output=json&key='.config('api.wx_map_key');
			$res = curl_send($url,[],[],false);
		
			if($res['status'] == 0){
				//$res['result']['routes'][0]['toll']   //过路费
				//打车费
				//$res['result']['routes'][0]['taxi_fare']['fare']
				$data['travel_price'] = 2*$res['result']['routes'][0]['taxi_fare']['fare'];
			}
		}
		$data['integral'] = User::where('id',$this->uid)->value('integral');
		$data['integral_money'] = Price::pricecalc($data['integral'],'*',Config::getConfig('integral_rate'),2);
		$data['balance'] = User::where('id',$this->uid)->value('balance');
		return show(200,'距离',$data);
	}
	/**
	 * 是否是白天
	 * [isDay description]
	 * @param  [type]  $scheduling_id [description]
	 * @return boolean                [description]  1白天 0晚上
	 */
	private function isDay($scheduling_id){
		$scheduling = Scheduling::get($scheduling_id);
		$start_time = $scheduling['start_time'];
		$start_date = strtotime(date('Y-m-d',$start_time) . ' 08:00:00');
		$end_date = strtotime(date('Y-m-d',$start_time) . ' 20:00:00');
		if($start_time >= $start_date && $start_time <= $end_date) return 1;
		return 0;
	}
	/*
	* 立即支付
	*/
	public function pay($order_id = 0) 
	{
		$data = myModel::alias('a')
                ->field('a.id,a.order_no,a.status,a.order_time,a.pay_status,a.order_money,b.openid,b.openid1')
                ->where('a.id',$order_id)
                ->leftjoin('user b','b.id=a.user_id')
                ->find();
        if(!$data){
            return show(400, "该订单不存在");
        }
        if($data['pay_status'] != 0 ){
            return show(400, "该订单已经支付", '该订单已经支付');
        }
        if($data->order_time > time()){
        	return show(400,'已超过服务时间,不可支付');
        }
  		$openid = $this->client == 1 ? $data['openid1'] : $data['openid'];
        $orderData = [
            'out_trade_no' => $data['order_no'] . mt_rand(1000, 9999),
            'body' => '订单支付',
            'total_fee' => Price::priceyuantofen($data['order_money']),
            'openid' => $openid,
            'trade_type' => 'JSAPI',
            'attach' => json_encode(['client' => $this->client]),
        ];

        try {
            $result = Pay::wechat(Config::getWechatConfig())->mp($orderData);
            myModel::where("id", $order_id)->update([
                'order_pay_no' => $orderData['out_trade_no'],
            ]);
            return show(200, "支付接口参数", $result);
        } catch (\Exception $e) {
            return show(500, "支付接口异常".$e->getMessage());
        }
	}
	/**
	 * 加项补差
	 * [plusOrder description]
	 * @param  [type] $order_id   [description]
	 * @param  [type] $plus_money [description]
	 * @return [type]             [description]
	 */
	public function plusOrder($order_id,$plus_money)
	{
		$data = myModel::alias('a')
                ->field('a.id,a.order_no,a.status,a.pay_status,a.order_money,b.openid,b.openid1')
                ->where('a.id',$order_id)
                ->leftjoin('user b','b.id=a.user_id')
                ->find();
        $openid = $this->client == 1 ? $data['openid1'] : $data['openid'];  
        $orderData = [
            'out_trade_no' => $data['order_no'] . mt_rand(1000, 9999),
            'body' => '服务加项支付',
            'total_fee' => Price::priceyuantofen($plus_money),
            'openid' => $openid,
            'trade_type' => 'JSAPI',
            'attach' => json_encode(['order_id' => $order_id,'client' => $this->client]),
        ];
        $config = Config::getWechatConfig();
        $config['notify_url'] = $config['plusorder'];
        try {
            $result = Pay::wechat($config)->mp($orderData);
            myModel::where(['id'=>$order_id])->update(['plus_pay_no'=>$orderData['out_trade_no']]);
            return show(200, "支付接口参数", $result);
        } catch (\Exception $e) {
            return show(500, "支付接口异常".$e->getMessage());
        }        
	}
	/**
	 * 退款说明
	 * [returnDesc description]
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function returnDesc($order_id)
	{
		$order = myModel::get($order_id);
		if($order['status'] < 2){    //未支付和待接单订单全额退款
			$list = [
				'status' => $order->status,
				'platform_service_money' => 0,
				'refund_travel_price' => 0,
				'delay_work_money' => 0,
			];
			return show(200,'退款说明',$list);
		}
        if($order->status == 5){
			return show(200,'退款说明',[
				'status' => $order->status,
				'appkey' => $order->refund_appkey,
				'service_money' => $order->service_money,
				'travel_price' => $order->travel_price,
				'platform_service_money' => $order->refund_appkey == 0 ? $order->platform_service_money : 0,
				'refund_travel_price' => $order->refund_appkey == 0 ? $order->refund_travel_price : 0,
				'delay_work_money' => $order->refund_appkey == 0 ? $order->delay_work_money : 0,
				'refund_money' => Price::pricecalc($order->tot_money,'-',$order->tot_platform)
			]);
		}


		$order_hour = Config::getConfig('order_hour');   //预约时间N小时前退款只扣除平台服务费
		$platform_service_rate = Config::getConfig('platform_service_rate');  //Y%  退款平台服务费率
		
		$order_time = strtotime($order->order_time);   //预约时间
		
		$is_order_hour = $order_time - $order_hour > time();  //false 小于N小时  ture大于N小时
		$platform_service_money = Price::pricecalc($order->tot_money,'*',$platform_service_rate);  //平台服务费
//		$refund_travel_price = 0;  //技师交通费用
//		$delay_work_money = 0;   //扣除技师误工费用
//		if(!$is_order_hour){   //小于N小时
			$refund_travel_price = $order->travel_price;
			$delay_work_money = Config::getConfig('delay_work_money');   //技师误工费
//		}
		$tot_platform = Price::pricecalc(Price::pricecalc($platform_service_money,'+',$refund_travel_price),'+',$delay_work_money);   //取消订单应扣除费用
		$list = [
            'status' => $order->status,
            'platform_service_money' => $platform_service_money,
            'refund_travel_price' => $refund_travel_price,
            'delay_work_money' => $delay_work_money,
        ];
        if($order->technician_service == 0){  //没出发
            $list = [
                'status' => $order->status,
                'platform_service_money' => $platform_service_money,
                'refund_travel_price' => 0,
                'delay_work_money' => 0,
            ];
        }else{  //已出发
            $list = [
                'status' => $order->status,
                'platform_service_money' => $platform_service_money,
                'refund_travel_price' => $refund_travel_price,
                'delay_work_money' => $delay_work_money,
            ];
        }
		return show(200,'退款说明',$list);
	}

	/**
	 * 取消订单， 未支付的直接删除
	 * [cancel description]
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function cancel($order_id)
	{
		$res = myModel::cancelOrder($order_id,$this->appkey);
		return show(200,'取消订单成功');
	}
	/**
	 * 通用接单
	 * [receivingOrder description]
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function receivingOrder($order_id)
	{
		$order = myModel::get($order_id);
		$technician = Technician::get($order->technician_id);
		if($order->receiving_order_type == 0 && $this->appkey == 1){
			return show(200,'等待商家接单');
		}
		$order_logs = [];
		if($order->receiving_order_type == 0 && $this->appkey == 2){
			$order->technician_status = 1;
			$order->status = 2;
		}
		if($order->receiving_order_type == 1 && $this->appkey == 1){
			$order->shop_status = 1;
			$order->status = 2;
		}
		if($this->appkey == 1){   //技师端接单
			$order->technician_status = 1;
			$order_logs = OrderLogs::create([
				'logs_type' => 0,
				'order_id' => $order->id,
				'contents0' => '技师确认接单，待上门服务',
				'contents1' => '技师确认接单',
				'contents2' => '技师确认接单',
				'mobile' => $technician['shop_mobile']
			]);
		}else{   //商家端接单
			$order_logs = OrderLogs::create([
				'logs_type' => 0,
				'order_id' => $order->id,
				'contents0' => '商家确认接单，待上门服务',
				'contents1' => '商家确认接单',
				'contents2' => '商家确认接单',
				'mobile' => $technician['shop_mobile']
			]);
			$order->shop_status = 1;
		}
		$order->receiving_time = time();
		$res = $order->save();

		if($res){
			if($order->status == 2){
				$model = new \app\lib\model\Ylysms();
				$rest = $model->sendTemplateSMS($order['mobile'],[],config('api.ylysms_complete_order_id'));
			}
			$res = Scheduling::where([['order_id','=',$order_id]])->update(['status'=>2,'update_time'=>time()]);
			return show(200,'接单成功');
		}
		return show(400,'接单失败');
	}
	/**
	 * 技师出发/已到达/开始服务/完成
	 * [setout description]
	 * @param  [type] $order_id  [description]
	 * @param  [type] $longitude [description]
	 * @param  [type] $latitude  [description]
	 * @return [type]            [description]
	 */
	public function setout($order_id,$technician_service,$longitude,$latitude)
	{
		$order = myModel::get($order_id);
		$technician = Technician::get($order->technician_id);
		Db::startTrans();
		$contents = $technician_service == 1 ? '技师已出发' : ($technician_service == 2 ? '技师已到达' : ($technician_service == 3 ? '技师开始服务' : '技师完成服务'));
		$order_logs = OrderLogs::create([
				'logs_type' => 0,
				'order_id' => $order_id,
				'contents0' => $contents,
				'contents1' => $contents,
				'contents2' => $contents,
				'mobile' => $technician['shop_mobile'],
				'longitude' => $longitude,
				'latitude' => $latitude
		]);
		if($order_logs->isEmpty()) return show(400,'失败');
		$order->technician_service = $technician_service;
		if($technician_service == 4){ //技师端完成
			$order->technician_status = 2;
			$order->technician_complete_time = time();
			$order->shop_status = 2;
			$order->status = 3;
		}
		if(!$order->save()){
			Db::rollback();
			return show(400,'失败');
		}
		Db::commit();
		return show(200,'成功');
	}
	/**
	 * 用户端完成订单
	 * [completeOrder description]
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function completeOrder($order_id)
	{
		$res = myModel::completeOrder($order_id);
		if($res){
			return show(200,'订单已完成');
		} 
		return show(400,'操作失败');
	}
	
}